/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blue.module;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 *
 * @author kelvio.matias
 */
public class DefaultModuleLoader implements ModuleLoader {

    @Override
    public void load(ModuleInfo moduleInfo) {
        //Load the required resources
        for (String resource : moduleInfo.getResources()) {
            System.out.println("Loading resource:" + resource);
            this.loadResource(new File(moduleInfo.getRootPath(), resource));
        }
        
        //Load the dependencies
        for (ModuleInfo dependency : moduleInfo.getDependencies()) {            
            this.load(dependency);
        }                
        this.runModule(moduleInfo);
    }

    private void runModule(ModuleInfo moduleInfo) {
        Method run = null;
        Object object = null;
        try {
            object = Class.forName(moduleInfo.getName() + ".Module").newInstance();
            run = object.getClass().getMethod("run");
            
        } catch (Exception e) {
            return;
        }
        try {
            run.invoke(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 
     * @param resource 
     */
    private void loadResource(File resource) {
        if (resource.getName().endsWith(".jar")) {
            this.addEntry(resource);
        }
    }
    
   
    /**
     * 
     * @param file 
     */
    private void addEntry(File file) {
        URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class sysclass = URLClassLoader.class;

        Method method = null;
        try {
            method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});
            method.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            URL e = new URL("file:" + file.getAbsolutePath());            
            method.invoke(sysloader, new Object[]{e});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
